package com.zuihai.app.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.zuihai.app.R;
import com.zuihai.app.mvp.constant.AppConfig;
import com.zuihai.app.mvp.model.api.service.MainService;
import com.zuihai.app.mvp.model.entity.mainhome.ColumnsDataSupport;
import com.zuihai.app.mvp.model.entity.mainhome.KPLogoSupport;
import com.zuihai.app.mvp.model.entity.mainhome.MainFirstDataSupport;
import com.zuihai.app.mvp.model.entity.mainhome.MainHomeClass;
import com.zuihai.app.mvp.model.entity.mainhome.MainHomeColumn;
import com.zuihai.app.mvp.model.entity.mainhome.MainHomeData;
import com.zuihai.app.mvp.model.entity.mainhome.MainHomeSubclass;
import com.zuihai.app.mvp.model.entity.mainhome.SubclassDataSupport;
import com.zuihai.app.mvp.ui.utils.MyUtils;
import com.zuihai.app.mvp.ui.utils.RetrofitUtils;
import com.zuihai.app.mvp.ui.widget.MyToast;

import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.concurrent.TimeUnit;

import retrofit2.Retrofit;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/30 0030.
 */
public class SplashActivity extends FragmentActivity {


    ImageView ivScreen;
    private SPUtils mSpUtils;
    private boolean isFirst;
    private Retrofit retrofit;
    private MainFirstDataSupport mData;
    private KPLogoSupport kplogo;
    private MainService regist;
    private List<KPLogoSupport> kpResouseData;
    private boolean isShowPicture =false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        init();
    }

    private void init() {
        ivScreen=findViewById(R.id.iv_screen);
        retrofit = RetrofitUtils.getPost();
        mData = new MainFirstDataSupport();
        kplogo=new KPLogoSupport();
        regist = retrofit.create(MainService.class);
        //开屏广告
        kpResouseData= DataSupport.findAll(KPLogoSupport.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        DataSupport.deleteAll(MainFirstDataSupport.class);
        DataSupport.deleteAll(ColumnsDataSupport.class);
        DataSupport.deleteAll(SubclassDataSupport.class);
        regist.mainItem()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MainHomeClass>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("onError : " + e.toString());
                    }

                    @Override
                    public void onNext(MainHomeClass mainHomeClass) {
                        //json-data
                        MainHomeData mainHomeData = mainHomeClass.getData();
                       /* if (mainHomeData.getKplogo()
                                .getPictureCommon().get(0)==null){
                            MyToast.showError("服务器异常,开盘广告为空");
                            return;
                        }
                        //设置开平广告
                        setKPAd(mainHomeClass, mainHomeData);*/
                        //保存秘密 推荐 logo图片
                        saveLogoTuijianImg(mainHomeClass, mainHomeData);

                        LogUtils.e("size : " + mainHomeClass.getData().getColumns().size());
                        if (mainHomeData.getColumns().size() > 0) {
                            for (int i = 0; i < mainHomeData.getColumns().size(); i++) {
                                //保存首页栏目的信息Bean
                                MainHomeColumn mainHomeColumn = mainHomeData.getColumns().get(i);
                                //保存数据库中的信息LitePal
                                ColumnsDataSupport mColumns = new ColumnsDataSupport();
                                mColumns.setCategory(mainHomeColumn.getCategory());
                                if (mainHomeColumn.getIcon().getM3x().length() > 1) {
                                    mColumns.setIcon(mainHomeColumn.getIcon().getM3x().toString());
                                } else {
                                    mColumns.setIcon(mainHomeColumn.getIcon().getM2x().toString());
                                }
                                mColumns.setItem_id(mainHomeColumn.getId());
                                mColumns.setLeibie(mainHomeColumn.getLeibie());
                                mColumns.setLevel(mainHomeColumn.getLevel());
                                mColumns.setName(mainHomeColumn.getName());
                                if (mainHomeColumn.getSelectedicon().getM3x().length() > 1) {
                                    mColumns.setSelectedIcon(mainHomeColumn.getSelectedicon().getM3x().toString());
                                } else {
                                    mColumns.setSelectedIcon(mainHomeColumn.getSelectedicon().getM2x().toString());
                                }
                                mColumns.setState(mainHomeColumn.getState());

                                //LogUtils.e("循环子类的数量是 ： " + mainHomeColumn.getSubclass().size());
                                //循环遍历Sub列的内容
                                for (int j = 0; j < mainHomeColumn.getSubclass().size(); j++) {
                                    //实体Bean
                                    MainHomeSubclass mMainSubclass = mainHomeColumn.getSubclass().get(j);

                                    //数据库LitePal
                                    SubclassDataSupport mSubclass = new SubclassDataSupport();
                                    mSubclass.setCategory(mMainSubclass.getCategory());
                                    mSubclass.setSubitem_id(mMainSubclass.getId());
                                    mSubclass.setLeibie(mMainSubclass.getLeibie());
                                    mSubclass.setLevel(mMainSubclass.getLevel());
                                    mSubclass.setName(mMainSubclass.getName());
                                    if (mMainSubclass.getIcon().getM3x().length() > 1) {
                                        mSubclass.setIcon(mMainSubclass.getIcon().getM3x().toString());
                                    } else {
                                        mSubclass.setIcon(mMainSubclass.getIcon().getM2x().toString());
                                    }
                                    if (mMainSubclass.getSelectedicon().getM3x().length() > 1) {
                                        mSubclass.setSelectedicon(mMainSubclass.getSelectedicon().getM3x().toString());
                                    } else {
                                        mSubclass.setSelectedicon(mMainSubclass.getSelectedicon().getM2x().toString());
                                    }
                                    mSubclass.setState(mMainSubclass.getState());
                                    mSubclass.save();


                                }
                                mColumns.save();
                                mData.getCommentList().add(mColumns);
                            }

                            if (mData.save()) {
                                LogUtils.e("保存完成");
                                mSpUtils = new SPUtils(AppConfig.SP_NAME);
                                isFirst = mSpUtils.getBoolean(AppConfig.IS_FIRST, true);
                                Observable.timer(2000, TimeUnit.MILLISECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Action1<Long>() {
                                            @Override
                                            public void call(Long aLong) {
                                                 skip();
                                            }
                                        });
                            } else {
                                LogUtils.e("faile save");
                            }
                        } else {
                            MyToast.showError("服务器数据异常");
                        }
                    }
                });

    }

    private void saveLogoTuijianImg(MainHomeClass mainHomeClass, MainHomeData mainHomeData) {
        //数据库保存Logo
        if (mainHomeData.getToplogo().getM3x().length() > 1) {
            mData.setTopLogo(mainHomeClass.getData().getToplogo().getM3x());
            LogUtils.e("setlogo**3X");
        } else {
            mData.setTopLogo(mainHomeClass.getData().getToplogo().getM2x());
            LogUtils.e("setlogo***2X");
        }

        //数据库保存首页推荐图
        if (mainHomeData.getHomeTjLogo().getM3x().length() > 1) {
            mData.setHomeTjLogo(mainHomeClass.getData().getHomeTjLogo().getM3x());
            LogUtils.e("setlogo**3X");
        } else {
            mData.setHomeTjLogo(mainHomeClass.getData().getHomeTjLogo().getM2x());
            LogUtils.e("setlogo***2X");
        }

        //数据库保存秘密推荐图
        if (mainHomeData.getMimiTjLogo().getM3x().length() > 1) {
            mData.setMimiTjLogo(mainHomeClass.getData().getMimiTjLogo().getM3x());
            LogUtils.e("setlogo**3X");
        } else {
            mData.setMimiTjLogo(mainHomeClass.getData().getMimiTjLogo().getM2x());
            LogUtils.e("setlogo***2X");
        }
    }

    private void setKPAd(MainHomeClass mainHomeClass, MainHomeData mainHomeData) {
        String kpUrl=mainHomeData.getKplogo()
                .getPictureCommon().get(0).getPictureUrl().toString();

        for (int i = 0; i < kpResouseData.size(); i++) {
            //获取数据库中每章图片的地址  准备和当前的地址作比较
            String picturlUrl=
                    kpResouseData.get(i).getPicture().toString();
            //如果两张图片是一样的 那么则加载图片并且安排跳转
            if (picturlUrl.equals(kpUrl)){
                isShowPicture =true;
            }
        }
        if (isShowPicture){
            LogUtils.e("加载一张加载过的图片");
            MyUtils.screenGlide(SplashActivity.this,kpUrl,ivScreen);
            ivScreen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                }
            });
        }else {
            kplogo.setDescription(mainHomeClass.getData().getKplogo().getDescription()+"");
            kplogo.setId(mainHomeClass.getData().getKplogo().getId()+"");
            kplogo.setTitle(mainHomeClass.getData().getKplogo().getTitle()+"");
            kplogo.setJumpUrl(mainHomeClass.getData().getKplogo().getJumpUrl()+"");
            kplogo.setPicture(mainHomeClass.getData().getKplogo().getPictureCommon().get(0).getPictureUrl()+"");

            if (kplogo.save()){
                LogUtils.e("这是一张新图片  保存数据库成功");
            }else{
                MyToast.showError("服务器异常,code:1001");
            }
        }
    }

    private void skip() {
        if (!isFirst) {
            if (isShowPicture){
                MainActivity.launchActivity(SplashActivity.this,false);
            }else {
                MainActivity.launchActivity(SplashActivity.this,true);
            }

        } else {
            mSpUtils.put(AppConfig.IS_FIRST, false);
            Intent intent = new Intent(SplashActivity.this, NavigationActivity.class);
            startActivity(intent);
        }
        finish();
    }
}
